<template>
  <!-- 年度投资金额各行业饼图 -->
  <div class="ProfessionChartPage">
    <div class="chartBox" :id="`perNumPie-${idName}-chart`"></div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import echarts from "@/common/utils/echarts.js";
import { percentApi, investNumApi } from "@/api-dashboard/investApi";

const props = defineProps({
  idName: {
    type: String,
    required: true, //必传属性
  },
});

const investProChartRef = ref(null);
// 各项颜色
const colorsLineArr = ref([
  "#1671C0",
  "#0FF1F4",
  "#C01616",
  "#34C016",
  "#0ABBFF",
  "#C016BA",
  "#F7CF8F",
  "#FF9AA1",
  "#FEFF82",
]);

// 图表 rich 所需数据格式转换
const changeRichData = () => {
  let result = {};
  colorsLineArr.value.forEach((v, i) => {
    result[`a${i}`] = {
      padding: [-11, 6, -20, 6],
      color: v,
      backgroundColor: "transparent",
      fontSize: props.idName === "moneyPer" ? 20 : 14,
    };
  });
  return result;
};
// 图表配置项
const options = reactive({
  legend: {
    orient: "vertical",
    top: "center",
    left: props.idName === "moneyPer" ? "60%" : "47%",
    itemGap: 4,
    itemHeight: 12,
    itemWidth: 12,
    // formatter: (params) => {
    //   let aim = legendFomartDataArr.value.find((item) => item.name == params);
    //   if (params.length > 5) {
    //     if (params.length > 10) {
    //       let str1 = params.substring(0, 5);
    //       let str2 = params.substring(5, 10);
    //       let str3 = params.substring(10, params.length);
    //       return `{name|${str1}}\n{name|${str2}}\n{name|${str3}}{number|${lile}}{unit|%}`;
    //     } else {
    //       let str1 = params.substring(0, 5);
    //       let str2 = params.substring(5, params.length);
    //       return `{name|${str1}}\n{name|${str2}}{number|${lile}}{unit|%}`;
    //     }
    //   }
    //   return `{name|${params}} {number|${lile}}{unit|%}`;
    // },
    textStyle: {
      lineHeight: 20,
      color: "#D3E3FF",
      // rich: {
      //   // legend的过滤条件
      //   name: {
      //     fontSize: 12,
      //     fontFamily: "PingFang-SC-Regular",
      //   },
      //   number: {
      //     fontSize: 12,
      //     fontFamily: "DS-Digital-Bold",
      //     padding: [0, 0, 0, 4],
      //   },
      //   unit: {
      //     fontSize: 12,
      //   },
      // },
    },
  },
  series: [
    {
      type: "pie",
      radius: props.idName === "moneyPer" ? ["90%", "65%"] : ["70%", "45%"],
      center: props.idName === "moneyPer" ? ["32%", "50%"] : ["20%", "50%"],
      clockwise: true,
      avoidLabelOverlap: true,
      label: {
        show: false,
        position: "center",
        formatter: function (params) {
          const name = params.name;
          let str1 = params.percent + ''
          let str2 = str1.split('.')[0]
          const percent = str2 + "%";
          const index = params.dataIndex;
          return [`{a${index}|${name}：${percent}}`]
        },
        rich: changeRichData(),
      },
      emphasis: {
        label: {
          show: true,
        },
      },
      itemStyle: {
        color: function (params) {
          return {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(0,180,255,.05)", // 0% 处的颜色
              },
              {
                offset: 1,
                color: colorsLineArr.value[params.dataIndex], // 100% 处的颜色
              },
            ],
            globalCoord: false, // 缺省为 false
          };
        },
      },
      data: [],
    },
    {
      name: "阴影圈",
      type: "pie",
      radius: props.idName === "moneyPer" ? ["0", "55%"] : ["0", "35%"],
      center: props.idName === "moneyPer" ? ["32%", "50%"] : ["20%", "50%"],
      emphasis: {
        scale: false,
      },
      tooltip: {
        show: false,
      },
      itemStyle: {
        color: "rgba(204,225,255, 0.05)",
      },
      zlevel: 4,
      labelLine: {
        show: false,
      },
      data: [100],
    },
  ],
});

// 请求数据，修改配置项
const legendFomartDataArr = ref([]);
const initProfessionChartData = (yearVal, typeVal) => {
  let paramObj = {
    year: yearVal,
    type: typeVal,
  };
  let getDataArr = [];
  // 请求拿到的数据，根据数值大小排序
  if (props.idName === "moneyPer") {
    // 请求‘年度投资金额各行业占比’接口
    percentApi.ndtzjeghyzb(paramObj).then((res) => {
      const { httpStatusCode, data } = res;
      if (httpStatusCode == 200 && data.records?.length) {
        data.records.map((n, i) => {
          getDataArr.push({
            name: n.field,
            value: n.proportion,
          });
        });
        getDataArr = getDataArr.sort((a, b) => {
          return b.value - a.value;
        });
        legendFomartDataArr.value = getDataArr;
        options.series[0].data = getDataArr;
        investProChartRef.value.setOption(options);
      }
    });
  } else {
    // 请求‘年度投资个数各行业占比’接口
    investNumApi.ndtzgsghyzb({ year: yearVal }).then((res) => {
      const { httpStatusCode, data } = res;
      if (httpStatusCode == 200 && data.records?.length) {
        data.records.map((n, i) => {
          getDataArr.push({
            name: n.field,
            value: n.proportion * 100,
          });
        });
        getDataArr = getDataArr.sort((a, b) => {
          return b.value - a.value;
        });
        legendFomartDataArr.value = getDataArr;
        options.series[0].data = getDataArr;
        investProChartRef.value.setOption(options);
      }
    });
  }
};

// 在父组件中调用
const initProfessionChart = (year, type) => {
  if (!investProChartRef.value) {
    investProChartRef.value = echarts.init(
      document.getElementById(`perNumPie-${props.idName}-chart`)
    );
    investProChartRef.value.setOption(options);
  }
  initProfessionChartData(year, type);
  return investProChartRef.value
};
defineExpose({
  initProfessionChart,
});
</script>

<style lang="scss" scoped>
.ProfessionChartPage {
  width: 100%;
  height: 90%;
  .chartBox {
    width: 100%;
    height: 100%;
  }
}
</style>
